//
//  ShopSearchViewController.m
//  BabyAndBaby
//
//  Created by 范琦 on 16/7/27.
//  Copyright © 2016年 范琦. All rights reserved.
//

#import "ShopSearchViewController.h"
#import "ShopSearchTopView.h"
#import "getDistrictModel.h"
#import "ShopViewCell.h"
#import "ShopModel.h"
#import "ShopDetailViewController.h"

@interface ShopSearchViewController ()<UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) ShopSearchTopView *topView;
@property (nonatomic, strong) NSMutableArray *pqArr;      //片区数组
@property (nonatomic, strong) UIPickerView *pickView;
@property (nonatomic, strong) UIView *pickTopView;
@property (nonatomic, strong) NSString *pqStr;      //片区数组
@property (nonatomic, strong) NSString *pqIdStr;      //片区数组
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *listArr;
@property (nonatomic, strong) UIView *noResultView;

@end

@implementation ShopSearchViewController

- (void)viewDidAppear:(BOOL)animated
{

}
- (void)loadView {
    [super loadView];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.tabBarController.tabBar.hidden = YES;

    
    return;
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];

    [super viewWillAppear:animated];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _pqArr = [NSMutableArray array];
    _listArr = [NSMutableArray array];
    [self creatTopView];
    [self getData];
    [self creatTableView];
    [self creatNoResultView];
}
- (void)creatNoResultView
{
    if (_noResultView == nil) {
        
        self.noResultView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, KSCREENWIDTH, KSCREENHEIGHT - 64)];
        _noResultView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(KSCREENWIDTH / 2 - 63, 200, 146, 147)];
        imageV.image = [UIImage imageNamed:@"空"];
        [_noResultView addSubview:imageV];
        [self.view addSubview:_noResultView];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 + 147 + 25, KSCREENWIDTH, 14)];
        label.text = @"无搜索结果";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:102 / 255.0 green:102 / 255.0 blue:102 / 255.0 alpha:1];
        label.textAlignment = NSTextAlignmentCenter;
        [_noResultView addSubview:label];
    }else{
        [self.view bringSubviewToFront:_noResultView];
    }
    
}
- (void)netHandle
{
    
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"/Merchant/merchantList.html" paramDic:@{@"area_id":_pqIdStr, @"token":TOKEN, @"name_merchant":_topView.text.text} RegisterApiMethod:RequestMethodGet];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([request.responseBody[@"error"] integerValue] == 0) {
            
            NSLog(@"%@", request.responseBody);
            NSArray *arr = request.responseBody[@"result"][@"data"];
            if (arr.count != 0) {
                for (NSDictionary *dic in arr) {
                    
                    ShopModel *model = [[ShopModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [_listArr addObject:model];
                    
                }
                [self.view bringSubviewToFront:_tableView];
                [_tableView reloadData];
            }else{
                [self.view bringSubviewToFront:_noResultView];

                [_listArr removeAllObjects];
                [_tableView reloadData];
            }
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];


}
#warning 片区信息请求
- (void)getData
{
    if (_pqArr.count == 0) {
        
        YTKNetHandle *api = [[YTKNetHandle alloc] initWithUrl:[NSString stringWithFormat:@"/Merchant/getMerchantArea.html?token=%@",TOKEN] RegisterApiMethod:RequestMethodGet];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            NSArray *arr = [request.responseBody objectForKey:@"result"];
            NSLog(@"%@", arr);
            for (NSDictionary *dic in arr) {
                getDistrictModel *model = [[getDistrictModel alloc] init];
                model.area_id = [dic objectForKey:@"area_id"];
                model.name = [dic objectForKey:@"name"];
                [self.pqArr addObject:model];
            }
            getDistrictModel *model =_pqArr[0];
            _pqStr = model.name;
            _pqIdStr = @"0";
            [_pickView reloadAllComponents];
        } failure:^(YTKBaseRequest *request) {
            
        }];
    }
}
- (void)creatTopView
{
    self.topView = [[[NSBundle mainBundle] loadNibNamed:@"ShopSearchTopView" owner:nil options:nil] lastObject];
    _topView.frame = CGRectMake(0, 20, KSCREENWIDTH, 44);
    [self.view addSubview:_topView];
    [[_topView.backBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [[_topView.pqBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self creatPickerView:_topView.pqBtn];
    }];
    [[_topView.searchBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self netHandle];
    }];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 20)];
    view.backgroundColor = BACKGROUNDCOLOR;
    [self.view addSubview:view];

}
- (void)creatTableView
{
    
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KSCREENWIDTH, KSCREENHEIGHT - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = HUIBACKGROUNDCOLOR;
        [_tableView registerNib:[UINib nibWithNibName:@"ShopViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        _tableView.rowHeight = 107;
        _tableView.sectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;

    [self.view addSubview:_tableView];
}
#warning 创建PickerView
- (void)creatPickerView:(UIButton *)btn
{
    if (_pickView == nil) {
        
        self.pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, KSCREENHEIGHT - 150, KSCREENWIDTH, 150)];
        _pickView.frame = CGRectMake(0, KSCREENHEIGHT - 144, KSCREENWIDTH, 144);
        _pickView.delegate = self;
        _pickView.dataSource = self;
        [self.view addSubview:_pickView];
        _pickView.backgroundColor = [UIColor huiseColor];
        
        self.pickTopView = [[UIView alloc]initWithFrame:CGRectMake(0, _pickView.frame.origin.y - 30, KSCREENWIDTH, 30)];
        [self.view addSubview:_pickTopView];
        _pickTopView.backgroundColor = HUIBACKGROUNDCOLOR;
        
    }else{
        [self.view addSubview:_pickView];
        [self.view addSubview:_pickTopView];
    }
    UIButton *done = [UIButton buttonWithType:UIButtonTypeSystem];
    [done setTitle:@"Done" forState:UIControlStateNormal];
    done.frame = CGRectMake(KSCREENWIDTH - 60, 0, 40, 30);
    done.tintColor = [UIColor blackColor];
    [_pickTopView addSubview:done];
    [[done rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [_pickView removeFromSuperview];
        [_pickTopView removeFromSuperview];
        _topView.pqLabel.text = _pqStr;
        
    }];
    
}

#warning TableView代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
 
    return _listArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 14;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 20)];
    view.backgroundColor = HUIBACKGROUNDCOLOR;
    return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    

            ShopModel *shop = _listArr[indexPath.section];
            cell.shopModel = shop;
            [[cell.phoneBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",[shop.user_name stringValue]];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }];

    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    

            ShopModel *shop = _listArr[indexPath.section];
            
            ShopDetailViewController *detail = [[ShopDetailViewController alloc]init];
            detail.str = [shop.myId stringValue];
            [self.navigationController pushViewController:detail animated:YES];

    
    
}
#warning PickerView代理方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    return _pqArr.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    getDistrictModel *model =_pqArr[row];
//    _pqIdStr = model.name;
    return model.name;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    getDistrictModel *model =_pqArr[row];
    _pqStr = model.name;
    _pqIdStr = [NSString stringWithFormat:@"%@", model.area_id];
}

// 使状态栏文字变为白色
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
